import UserService from '../service/user.js';

const USER_KEY = 'user';



const state = {
	//初始化数据，优先从本地存储获取
	userInfo: uni.getStorageSync(USER_KEY) || {},
	isLogin: false
}


const actions = {
	async login({
		commit,
		state
	}, loginData) {
		const res = await UserService.loginService(loginData)
		commit('setLoginStatus', true)
		commit('setUser', res)
		return res
	},
	async register({
		commit,
		state
	}, registerData) {
		const response = await UserService.registerService(registerData)
		return response
	},
	
	// 实名认证状态修改
	changIsRealAction({commit, state}){
		commit('changIsReal')
	},
	
	loginOut({commit, state}) {
		commit('setLogout')
	},
	async updatePassword({
		commit,
		state
	}, updateData) {
		const response = await UserService.updateLoginPassword(updateData)
		if (response) {
			uni.showLoading({
				title: '密码修改成功'
			});
			setInterval(() => {
				uni.hideLoading();
				commit('setLogout')

			}, 1000)
		}
	},
	// 更新用户数据
	async updateUserByid({
		commit,
		state
	}, params) {
		const response = await UserService.getUserById(params)
		if (response) {
			commit('updateUser', response)
		}
	},

	async updateNewPhone({
		commit,
		state
	}, updateData) {
		const response = await UserService.updateNewPhone(updateData)
		if (response) {
			uni.showLoading({
				title: '更改手机号成功'
			});
			setTimeout(() => {
				uni.hideLoading();
				commit('setLogout')
			}, 1000)
		}
	},
	async updatePay({
		commit,
		state
	}, updateData) {
		const response = await UserService.updatePayPassword(updateData)
		if (response) {
			uni.showLoading({
				title: '支付密码设置成功'
			});
			setTimeout(() => {
				uni.hideLoading();
				uni.navigateBack()
			}, 1000)
		}
	},

}


const mutations = {
	setUser(state, res) {
		state.userInfo = res
		uni.setStorageSync(USER_KEY, res);
		uni.setStorageSync('token', res.token);
		
		
	},

	setLoginStatus(state, status) {
		state.loginStatus = status
	},

	setLogout(state) {
		state.loginStatus = false
		state.userInfo = {}
		uni.removeStorageSync(USER_KEY)
		uni.removeStorageSync('token')
		uni.reLaunch({
			url: '/pages/login/login'
		})
	},
	updateUser(state, user) {
		state.userInfo = user
		uni.setStorageSync(USER_KEY, user);
	},
	changIsReal(state){
		const user = state.userInfo
		state.userInfo = {
			...state.userInfo,
			isreal:1
		}
		uni.setStorageSync(USER_KEY, user);
	},
}

export default {
	mutations,
	state,
	actions
}
